import re
from pathlib import Path
from typing import Any, Dict, List, Tuple

import yaml


def read_text(path: str) -> str:
    p = Path(path)
    return p.read_text(encoding="utf-8")


def parse_front_matter(text: str) -> Tuple[Dict[str, Any], str]:
    m = re.match(r"\A---\s*\n([\s\S]*?)\n---\s*\n", text)
    if not m:
        return {}, text
    fm = yaml.safe_load(m.group(1)) or {}
    rest = text[m.end():]
    return fm, rest


def parse_yaml_blocks(text: str) -> List[Dict[str, Any]]:
    blocks = []
    for m in re.finditer(r"```yaml\s*\n([\s\S]*?)\n```", text):
        data = yaml.safe_load(m.group(1)) or {}
        blocks.append(data)
    return blocks


def load_markdown(path: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
    text = read_text(path)
    fm, rest = parse_front_matter(text)
    pages = parse_yaml_blocks(rest)
    return fm, pages